package com.yang.handler;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yang.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis plus自动填充
 *
 * @Author: 不是菜鸡爱编程
 * @Date: 2024/02/16/22:01
 * @Description:
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        User user = UserThreadLocal.get();
        this.strictInsertFill(metaObject, "nickName", String.class, "默认昵称" + IdUtil.simpleUUID());
        this.strictInsertFill(metaObject, "gender", Integer.class, 1);
        this.strictInsertFill(metaObject, "isAdmin", Integer.class, 1);
        this.strictInsertFill(metaObject, "header", String.class, "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
        if(ObjUtil.isNotNull(user)){
            this.strictUpdateFill(metaObject, "createBy", Integer.class, user.getId());
            this.strictUpdateFill(metaObject, "updateBy", Integer.class, user.getId());
        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "delFlag", Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        User user = UserThreadLocal.get();
        if(ObjUtil.isNotNull(user)){
            this.strictUpdateFill(metaObject, "updateBy", Integer.class, user.getId());
        }
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}
